﻿using System;
using System.Windows.Forms;
using Aspects.Unit;

namespace Aspects.Panels.Main_Panels
{
    public partial class MagStripeReaderPanel : Panel
    {
        MagStripeReader msr;
        public MagStripeReaderPanel()
        {
            InitializeComponent();
        }

        public void SetupPointOfSale()
        {
            msr = new MagStripeReader();
            if (!string.IsNullOrEmpty(msr.ComPort))
            {
                if (MsrPort.IsOpen)
                    MsrPort.Close();

                MsrPort.PortName = msr.ComPort;
                MsrPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(MsrPort_DataReceived);
                try
                {
                    MsrPort.Open();
                    Console.WriteLine("MSR Active");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        private void MsrPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //msr
            int bytesRead = MsrPort.BytesToRead;
            byte[] buffer = new byte[bytesRead];
            MsrPort.Read(buffer, 0, bytesRead);

            msr.ReadCard(buffer);

            if (msr.DataReady)
                PopulateMagStripeInformation();
            else
                ClearMagStripeInformation();
            
        }

        private void PopulateMagStripeInformation()
        {
            track1Label.Text = msr.Track1;
            track2Label.Text = msr.Track2;
            track3Label.Text = msr.Track3;
            track4Label.Text = msr.Track4;
            firstNameLabel.Text = msr.FirstName;
            middleNameLabel.Text = msr.MiddleName;
            lastNameLabel.Text = msr.LastName;
            accountLabel.Text = msr.Account;
            expirationLabel.Text = msr.Expiration;
            serviceCodeLabel.Text = msr.ServiceCode;
        }

        private void ClearMagStripeInformation()
        {
            track1Label.Text = null;
            track2Label.Text = null;
            track3Label.Text = null;
            track4Label.Text = null;
            firstNameLabel.Text = null;
            middleNameLabel.Text = null;
            lastNameLabel.Text = null;
            accountLabel.Text = null;
            expirationLabel.Text = null;
            serviceCodeLabel.Text = null;
        }

    }
}
